package com.vincent.aop;

import com.vincent.exception.InValidParamException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;

/**
 * Created by Vincent on 2015/1/7.
 */
@Component
@Aspect
public class VoErrorsAop {
    @Pointcut("execution(* com.vincent.controller.*.*.*(..))")
    public void aspect(){}

    @Around("aspect()")
    public Object before(ProceedingJoinPoint point) {
        Object[] args = point.getArgs();
        for (Object object : args) {
            if (object!=null&&object.getClass().equals(BeanPropertyBindingResult.class)) {
                BeanPropertyBindingResult errors = (BeanPropertyBindingResult) object;
                if(errors.hasErrors()){
                    throw new InValidParamException(errors.getFieldError().getDefaultMessage());
                }
            }
        }
        try {
            return point.proceed();
        } catch (Throwable throwable) {
            throw new RuntimeException("运行异常",throwable);
        }
    }
}
